<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2024/5/23} {18:01} 
 */

namespace wanghua\general_utility_tools_php\websocket;


use GatewayWorker\Lib\Gateway;
use think\Db;
use wanghua\general_utility_tools_php\tool\Tools;

/**
 * websocket业务逻辑路由控制
 *
 * 【重要提示】websocket业务逻辑类只能放在应用app/api/logic/目录中，由事件初始化并自动加载
 *
 * 提示：
 * 该类无需重写和扩展，由BaseEvents.php初始化执行调用
 *
 * Class BaseWebsocketLogic
 * @package wanghua\general_utility_tools_php\websocket
 */
class BaseWebsocketLogic
{
    function domsg($client_id, $data){
        try {
            $res = @json_decode($data, true);
            Tools::log_to_write_txt(['json_decode:', $res]);
            if (!$res) {
                $json = Tools::json_wss('error', '消息格式错误');
                Gateway::sendToClient($client_id, $json);
                return;
            }
            if (empty($res['action'])) {
                $json = Tools::json_wss('error', '消息格式错误，action必须');
                Gateway::sendToClient($client_id, $json);
                return;
            }
            $act_arr = explode('/', $res['action']);
            if (empty($act_arr[0])) {
                $json = Tools::json_wss('error', '错误的action格式');
                Gateway::sendToClient($client_id, $json);
                return;
            }
            if (empty($act_arr[1])) {
                $json = Tools::json_wss('error', '错误的action格式！');
                Gateway::sendToClient($client_id, $json);
                return;
            }
            //根据action执行业务逻辑
            $controller = ucfirst($act_arr[0]);
            $function = $act_arr[1];
            $namespace = '\\app\\api\\logic\\' . $controller . 'Logic';
            $obj = $this->getinstance($namespace);
            $obj->$function($client_id, $res);
        } catch (\Exception $e) {
            Tools::error_txt_log($e);
            $json = Tools::json_wss('error', '服务繁忙');
            Gateway::sendToClient($client_id, $json);
        }
    }

    function getinstance($className)
    {
        // 类名字符串
        // 参数数组

        // 确保类存在
        if (!class_exists($className)) {
            throw new \InvalidArgumentException("Class {$className} does not exist.");
        }
        // 创建反射类实例
        $reflection = new \ReflectionClass($className);

        // 检查构造函数是否存在
        //if (!$reflection->hasMethod('__construct')) {
        //    throw new \LogicException("Class {$className} has no constructor.");
        //}
        //$constructor = $reflection->getConstructor();

        // 如果构造函数有参数，我们需要匹配参数
        //if ($constructor !== null) {
        //    $constructorParams = $constructor->getParameters();
        //
        //    // 确保参数数量匹配
        //    if (count($constructorParams) !== count($params)) {
        //        throw new \InvalidArgumentException("Number of constructor parameters does not match provided arguments.");
        //
        //    }
        //    // 创建参数数组，将参数类型与值匹配
        //    $matchedParams = [];
        //    foreach ($constructorParams as $index => $param) {
        //        // 如果参数允许null，或者参数类型与传递的值兼容，添加到匹配参数数组
        //        if ($param->allowsNull() || $param->getClass() === null || $param->getClass()->isInstance($params[$index])) {
        //            $matchedParams[] = $params[$index];
        //        } else {
        //            throw new \InvalidArgumentException("Provided argument does not match constructor parameter type at position {$index}.");
        //        }
        //    }
        //    // 使用反射类创建并初始化类实例
        //    $instance = $reflection->newInstanceArgs($matchedParams);
        //} else {
        //
        //}
        // 构造函数无参数，直接创建实例
        $instance = $reflection->newInstanceWithoutConstructor();
        return $instance;
    }

}